<?php

namespace app\api\controller\mine;

use app\api\model\common\CoinModel;
use app\api\model\common\OrePoolModel;
use app\api\model\mine\ComputingPowerModel;
use app\api\model\mine\MiningMachineModel;
use app\api\model\order\OrderMiningModel;
use app\api\request\index\HomeRequest;
use app\api\request\mine\MiningRequest;
use app\common\controller\Api;
use think\Loader;

class Mining extends Api
{
    protected $noNeedLogin = ['list'];
    protected $noNeedRight = ['*'];

    /**
     * Notes: 获取币种列表
     * User: 浪子膏
     * Date: 2023/10/30 15:50
     * @throws \think\exception\DbException
     */
    public function list()
    {
        $params = request()->post();
        $validate = Loader::validate(MiningRequest::class);
        if (!$validate->scene('list')->check($params)) $this->error($validate->getError());

        $miningMachineModel = new MiningMachineModel();
        $list = $miningMachineModel->where('coin_id', $params['coin_id'])
            ->order('create_time desc')->paginate($params['page_size'] ?? 15)->each(function ($item) {
                $coin = CoinModel::where('id', $item['coin_id'])->find();
                $item['price'] = floatval($item['price']);
                $item['computing_power'] = floatval($item['computing_power']);

                $sum_electric_charge_day = round($item['electricity_bill'] * $item['power'] * 24 * $item['period'], 10);//当日电费
                $item['static_rate'] = round(($item['period'] * $item['computing_power']
                        * $coin['per_unit'] * $coin['coin_price_usd'] - $sum_electric_charge_day) / $item['price'] * 100, 2);
                $item['sum_electric_charge_day'] = $sum_electric_charge_day;
                $item['computing_power'] = floatval($item['computing_power']).$coin['reward_unit'];
//                $item['预计挖矿'] = $item['period'] * $item['computing_power']
//                    * $coin['per_unit'] * $coin['coin_price_usd'] ;
//                $item['法比价格']  = $coin['coin_price_usd'];
//                $item['服务费']  = $item['price'];
            });

        $this->dataOk($list);

    }

    /**
     * Notes: 矿机详情
     * User: 浪子膏
     * Date: 2023/10/30 16:38
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function info()
    {
        $params = request()->post();
        $validate = Loader::validate(MiningRequest::class);
        if (!$validate->scene('info')->check($params)) $this->error($validate->getError());

        $miningMachineModel = new MiningMachineModel();
        $info = $miningMachineModel->where('id', $params['id'])->find();

        if (empty($info)) {
            $this->error(__('That information no longer exists'));
        }
        $info['coin'] = CoinModel::where('id', $info['coin_id'])->find();
        $info['pool'] = OrePoolModel::where('id', 1)->find();


        if ($info['period'] == 0) {
            $info['period'] = 3650;
        }
        $info['sum_electric_charge_day'] = round($info['electricity_bill'] * $info['power'] * 24 * $info['period'], 10);//总电费

        $info['static_rate'] = round(($info['period'] * $info['computing_power']
                    * $info['coin']['per_unit'] * $info['coin']['coin_price_usd'] - $info['sum_electric_charge_day']) / $info['price'] * 100, 2);  //静态收益率
        $info['projected_income'] = round($info['period'] * $info['computing_power']
            * $info['coin']['per_unit'], 8); // 预计挖矿

        $info['payback_days'] = ceil($info['price'] / ($info['projected_income'] * $info['coin']['coin_price_usd']
                - $info['sum_electric_charge_day']) * $info['period']);//回本天数

        $info['computing_power'] = floatval($info['computing_power']) . $info['coin']['reward_unit'];
        $info['power'] = floatval($info['power']);
        $info['price'] = floatval($info['price']);
        $this->dataOk($info);
    }

    /**
     * Notes: 预计挖矿详情
     * User: 浪子膏
     * Date: 2023/11/9 16:52
     */
    public function earnings()
    {
        $params = request()->post();
        $validate = Loader::validate(MiningRequest::class);
        if (!$validate->scene('earnings')->check($params)) $this->error($validate->getError());

        $miningMachineModel = new MiningMachineModel();
        $info = $miningMachineModel->alias('m')->join('coin c', 'c.id = m.coin_id')
            ->field('m.id,m.computing_power,m.power,m.algorithm,m.electricity_bill,c.coin_type,c.per_unit,c.mining_addr_list')
            ->find();
        if (empty($info)) {
            $this->error(__('That information no longer exists'));
        }

        if (!empty($info['mining_addr_list'])) {
            $info['mining_addr_list'] = json_decode($info['mining_addr_list'], true);
        }
        $info['day_price'] = round($info['computing_power'] * $info['per_unit'], 10);

        $data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
        $map = [];
        foreach ($data as $key => $value) {
            $map[] = [
                'hour' => $value,
                'computing_power' => $info['computing_power'] * rand(50, 100) / 100,
            ];
        }

        $info['map'] = $map;
        $this->dataOk($info);

    }

    public function allMining()
    {
        $params = request()->post();
        $validate = Loader::validate(MiningRequest::class);
        if (!$validate->scene('allMining')->check($params)) $this->error($validate->getError());

        $coinModel = new CoinModel();
        $coin = $coinModel->where('id', $params['id'])->find();
        if (empty($coin)) {
            $this->error(__('That information no longer exists'));
        }
        $data['coin'] = $coin;
        $data['mining_addr_list'] = '';
        $data['sum_computing_power'] = 0;
        $data['day_price'] = 0;

        if (!empty($coin['mining_addr_list'])) {
            $data['mining_addr_list'] = json_decode($coin['mining_addr_list'], true);
        }
        $data['make_money_time'] = __('Strike time');
        $orderMiningModel = new OrderMiningModel();
        $list = $orderMiningModel->where('coin_id', $params['id'])->where('user_id', $this->auth->id)
            ->where('status', OrderMiningModel::STATUS_PAY)
            ->select();

        $data['map'] = [];
        if (count($list) > 0) {
            foreach ($list as $item) {
                $data['sum_computing_power'] += $item['computing_power'];
                $data['day_price'] += round($item['computing_power'] * $coin['per_unit'], 10);
            }

            $computingPowerModel = new ComputingPowerModel();
            $rangeList = $computingPowerModel->where(['user_id'=>$this->auth->id,'coin_id'=>$params['id']])
                ->limit(12)
                ->order('create_time desc')
                ->select();

            $map = [];
            foreach ($rangeList as $key => $value) {
                $map[] = [
                    'hour' => $value['hour'],
                    'computing_power' => $data['sum_computing_power'] * $value['range'],
                ];
            }

            $data['sum_computing_power'] .= $coin['net_hashrate_unit'];
            $data['day_price'] .= $coin['coin_type'];
            $data['map'] = $map;
        }


        $this->dataOk($data);

    }

}